package com.zhanghu.backendZray.exception;

import cn.hutool.core.util.StrUtil;
import com.zhanghu.backendZray.pojo.dto.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ZhangDong
 * @date 2023/8/28 17:14
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class ExceptionAdvice {

    @ExceptionHandler(value = ApiException.class)
    public ApiResponse apiException(HttpServletRequest request, ApiException e) {
        return ApiResponse.error(e.getStatus(), e.getMessage());
    }

//    @ExceptionHandler(value = ConstraintViolationException.class)
//    public ApiResponse constraintViolationException(HttpServletRequest request, ConstraintViolationException e) {
//        return ApiResponse.error(e.getMessage());
//    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ApiResponse methodArgumentNotValidException(HttpServletRequest request, MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        return ApiResponse.error(bindingResult.getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public ApiResponse exception(HttpServletRequest request, Exception e) {
        log.error("exception:{}", e);
        String message = e.getMessage();
        if (StrUtil.isNotEmpty(message) && message.contains("Duplicate entry")) {
            return ApiResponse.error("数据已存在，请勿重复添加");
        }
        return ApiResponse.error(e.getMessage());
    }
}
